<template>
	<view class="canvas-content">
		<view class="canvas-mask" v-if="!onlyShare"></view>
		<view class="preview-panel" :style="{visibility: onlyShare ? 'hidden' : 'visible', zIndex: onlyShare ? -1 : 100}">
			<view class="preview-panel-header">预览</view>
			<view class="preview-panel-body"><img v-if="tempFilePath" :style="{ height: height + 'rpx' }" class="panel-image" :src="tempFilePath" /></view>
			<view class="preview-panel-footer">
				<button @click="close">关闭</button>
				<text style="width: 2rpx;height: 50rpx;background: rgba(102, 100, 93, 0.15);margin: 20rpx 0;"></text>
				<!-- #ifdef MP-WEIXIN -->
				<button @click="downloadSharePhoto" :disabled="shareButton">保存</button>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<button @click="downloadSharePhoto" :disabled="shareButton">分享</button>
				<!-- #endif -->
			</view>
		</view>
		<loading ref="loading"></loading>
		<!-- #ifdef H5 -->
		<view ref="canvasContainer"></view>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<canvas class="canvas" canvas-id="cardCanvas" :style="{ width: `${canvas.width}px`, height: `${canvas.height}px` }"></canvas>
		<!-- #endif -->
	</view>
</template>

<script>
import bridgeApi from '../../common/rayBridgeSDK.js';
import { getWxShareHref } from '../../common/utils.js';
import http, { uploadImages } from '../../common/request.js';
import Loading from '@/components/notice/loading.vue';
import h5 from './h5.js'
import mp from './mp.js'
export default {
	mixins: [
		// #ifdef MP-WEIXIN
		mp
		// #endif
		// #ifdef H5
		h5
		// #endif
	],
	components: { Loading },
	data() {
		const info = uni.getSystemInfoSync();
		return {
			ctx: undefined,
			tempFilePath: '',
			showShare: false,
			shareButton: true,
			canvas: {
				el: undefined,
				width: 750,
				height: 390,
				pixelRatio: info.pixelRatio
			},
			width: 375,
			height: 350,
			attrs: {
				date: [],
				radius: 20,
				fillColor: '#ffffff',
				innerLR: 28,
				innerTB: 0,
				planImageUrl: '',
				imageUrl: '',
				posterRatio: 1.8,
				planRatio: 2.46,
				logoUrl: '',
				title: '',
				codeUrl: '',
				userName: ''
			}
		};
	},
	props: {
		params: {
			type: Object
		},
		onlyShare: {
			type: Boolean,
			default: true
		},
		dirayId: {
			type: String
		},
		planClockId: {
			type: String
		}
	},
	watch: {
		params: {
			handler(val) {
				if (val && val.title) {
					//通过title判断是否有效
					Object.assign(this.attrs, val);
					// this.$nextTick(() => {
					// 	this.creatPoster();
					// })
				}
			},
			deep: true,
			immediate: true
		},
		onlyShare: {
			handler(val) {
				if(val === false) {
					const query = uni.createSelectorQuery().in(this),
						that = this;
					query
						.select('.preview-panel-body')
						.boundingClientRect(rect => {
							that.width = rect.width;
							that.$nextTick(() => {
								that.creatPoster();
							})
						})
						.exec();
				}
			}
		}
	},
	mounted() {
		// const query = uni.createSelectorQuery().in(this),
		// 	that = this;
		// query
		// 	.select('.preview-panel-body')
		// 	.boundingClientRect(rect => {
		// 		that.width = rect.width;
		// 		that.creatPoster();
		// 	})
		// 	.exec();
	},
	methods: {
		
		base64ToUrl(base64) {
			return uploadImages('/fastdfs/upload/multiUploadPath?_=' + Date.now(), { fileList: [{ name: 'file', uri: base64 }] }).then(result => {
				return JSON.parse(result[0]).msg;
			});
		},
		shareCardAdd() {
			http('/api/sysThemePunchPlan/share/', {
				data: {
					planClockId: this.planClockId
				},
				method: 'POST'
			});
		},
		getDynamicHeight() {
			const {
				ctx,
				attrs,
				canvas
			} = this;
			// #ifdef MP-WEIXIN
			ctx.setFontSize(26)
			// #endif
			// #ifdef H5
			ctx.font = '26px PingFangSC-Regular';
			// #endif
			const list = attrs.title.split('\n');
			let textY = 0;
			for (let text of list) {
				if (text) {
					textY += this.drawText({
						text: text,
						left: attrs.innerLR + 51,
						lineHeight: 42,
						top: textY,
						maxWidth: canvas.width - 2 * attrs.innerLR - 178
					}) - textY;
					textY += 42;
				}
			}
			return textY - 42;
		},
		getImageHeight(image, canvas, attrs){
			const height = image.height * (canvas.width - attrs.innerLR) / image.width;
			return height
		},
		async creatPoster() {
			this.$refs.loading.show('生成中');
			const {
				attrs,
				canvas
			} = this;
			// #ifdef MP-WEIXIN
			this.ctx = uni.createCanvasContext('cardCanvas', this);
			// #endif
			// #ifdef H5
			this.ctx = this.createCanvas();
			// #endif
			this.masterImage = await this.getImageInfo(attrs.imageUrl);
			this.planImage = await this.getImageInfo(attrs.planImageUrl);
			const mHeight = this.getImageHeight(this.masterImage, canvas, attrs);
			const pHeight = this.getImageHeight(this.planImage, canvas, attrs);
			const textHeight = this.getDynamicHeight();
			canvas.height += textHeight + mHeight + pHeight;
			this.height = (canvas.height * 590) / canvas.width;
			// #ifdef H5
			this.ctx = this.createCanvas();
			// #endif
			this.ctx.save();
			// 根据设备屏幕大小和距离屏幕上下左右距离，及圆角绘制背景
			this.roundRect(0, 0, canvas.width, canvas.height, attrs.radius, '#ffffff', [false, false, false, false]);
			this.ctx.restore();
			//绘制标题 top 绘制文本的y位置
			let top = attrs.innerTB;
			await this.drawLogo(top);
			top = this.drawDate(top);
			//绘制海报图片
			top = await this.drawImage(top, {
				img: this.planImage,
				ratio: attrs.planRatio,
				radius: attrs.radius,
				marginTop: 60
			});
			//绘制海报图片
			top = await this.drawImage(top, {
				img: this.masterImage,
				ratio: attrs.posterRatio,
				radius: attrs.radius,
				marginTop: 10
			});
			// 绘制标题 top 绘制文本的y位置
			top = this.drawContent(top) + textHeight;
			// 小程序的名称
			this.drawName(top);
			// 绘制小程序码
			await this.drawQRCode(top);
			//将海报转化为图片
			// #ifdef MP-WEIXIN
			this.ctx.draw(true, r => {
				this.saveToImage();
			});
			// #endif
			// #ifdef H5
			this.saveToImage();
			// #endif
		},
		async drawLogo(top) {
			const {
				ctx,
				attrs,
				canvas
			} = this;
			const left = canvas.width - 310 - attrs.innerLR;
			if (!attrs.logoUrl) {
				return Promise.resolve();
			}
			const info = await this.getImageInfo(attrs.logoUrl);
			if (info) {
				ctx.save();
				// #ifdef MP-WEIXIN
				ctx.drawImage(info.path, 0, 0, info.width, info.height, left, top + 48, 310, 36);
				// #endif
				// #ifdef H5
				ctx.drawImage(info.image, 0, 0, info.width, info.height, left, top + 48, 310, 36);
				// #endif
				ctx.restore();
			}
		},
		async drawImage(top, {
			img,
			ratio,
			marginTop = 45
		}) {
			top += marginTop;
			const {
				ctx,
				attrs,
				canvas
			} = this;
			let width = canvas.width - 2 * attrs.innerLR;
			let height = this.getImageHeight(img, canvas, attrs);
			ctx.save();
			this.roundRect(attrs.innerLR, top, width, height, attrs.radius);
			// #ifdef MP-WEIXIN
			ctx.drawImage(img.path, 0, 0, img.width, img.height, attrs.innerLR, top, width, height);
			// #endif
			// #ifdef H5
			ctx.drawImage(img.image, 0, 0, img.width, img.height, attrs.innerLR, top, width, height);
			// #endif
			ctx.restore();
			return height + top;
		},
		drawContent(top) {
			top += 52;
			const {
				ctx,
				attrs,
				canvas
			} = this;
			// #ifdef MP-WEIXIN
			ctx.setFontSize(26)
			// #endif
			// #ifdef H5
			ctx.font = '26px PingFangSC-Regular';
			// #endif
			const list = attrs.title.split('\n');
			let textY = 0;
			ctx.save();
			for (let text of list) {
				if (text) {
					textY += this.drawText({
						text: text,
						left: attrs.innerLR + 51,
						lineHeight: 42,
						top: top + textY,
						maxWidth: canvas.width - 2 * attrs.innerLR - 178
					}) - top - textY;
					textY += 42;
				}
			}
			ctx.restore();
			return top;
		},
		drawText({
			text = '',
			left,
			top,
			lineHeight = 45,
			maxWidth,
			textAlign = 'left',
			color = '#65645D'
		}) {
			const {
				ctx,
				canvas,
				attrs
			} = this;
			top += lineHeight / 2;
			maxWidth = maxWidth || canvas.width - 2 * attrs.innerLR;
			ctx.fillStyle = color;
			// 设置垂直对齐方式
			let arrText = text.split('');
			let line = '';
			for (let i = 0; i < arrText.length; i++) {
				let textLine = line + arrText[i];
				let metrics = ctx.measureText(textLine);
				if (metrics.width > maxWidth && i > 0) {
					ctx.fillText(line, left, top);
					line = arrText[i];
					top += lineHeight;
				} else {
					line = textLine;
				}
			}
			if (textAlign === 'left') {
				ctx.fillText(line, left, top);
			} else if (textAlign === 'center') {
				ctx.textAlign = textAlign;
				ctx.fillText(line, canvas.width / 2, top);
			}
			return top;
		},
		drawName(top) {
			top += 68;
			const {
				ctx,
				attrs,
				canvas
			} = this;
			ctx.save();
			// #ifdef MP-WEIXIN
			ctx.setFontSize(22)
			// #endif
			// #ifdef H5
			ctx.font = '22px PingFangSC-Regular';
			// #endif
			let textY = this.drawText({
				text: attrs.userName || '',
				left: attrs.innerLR + 51,
				top,
				lineHeight: 42
			});
			ctx.restore();
			return textY;
		},
		async drawQRCode(textY) {
			const {
				ctx,
				attrs,
				canvas
			} = this;
			if (!attrs.codeUrl) {
				return Promise.resolve();
			}

			const info = await this.getImageInfo(attrs.codeUrl);
			if (info) {
				ctx.save();
				// #ifdef MP-WEIXIN
				ctx.drawImage(info.path, 0, 0, info.width, info.height, canvas.width - 120 - 84, textY + 25, 120, 120);
				// #endif
				// #ifdef H5
				ctx.drawImage(info.image, 0, 0, info.width, info.height, canvas.width - 120 - 84, textY + 25, 120, 120);
				// #endif
				ctx.restore();
			}
		},
		roundRect(x, y, w, h, r, fillColor = '#ffffff', lineStatus = [true, true, true, true]) {
			const { ctx } = this;
			ctx.save();
			ctx.beginPath();
			// 绘制左上角圆弧
			if (lineStatus[0]) {
				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
				// 绘制border-top
				ctx.lineTo(x + w - r, y);
			} else {
				// 绘制border-top
				ctx.lineTo(x + w - r, y);
			}
			// 绘制右上角圆弧
			if (lineStatus[1]) {
				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
				// 绘制border-right
				ctx.lineTo(x + w, y + h - r);
			} else {
				// 不全border-top
				ctx.lineTo(x + w, y);
				// 绘制border-right
				ctx.lineTo(x + w, y + h - r);
			}
			// 绘制右下角圆弧
			if (lineStatus[2]) {
				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
				// 绘制border-bottom
				ctx.lineTo(x + r, y + h);
			} else {
				// 不全border-right
				ctx.lineTo(x + w, y + h);
				// 绘制border-bottom
				ctx.lineTo(x, y + h);
			}

			// 绘制左下角圆弧
			if (lineStatus[3]) {
				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
				// 绘制border-left
				ctx.lineTo(x, y + r);
			} else {
				// 不全border-right
				ctx.lineTo(x, y + h);
				// 绘制border-bottom
				ctx.lineTo(x, y);
			}
			// 填充颜色
			ctx.fillStyle = fillColor;
			ctx.fill();
			// 剪切，剪切之后的绘画绘制剪切区域内进行，需要save与restore 这个很重要 不然没办法保存
			ctx.clip();
		},
		close() {
			this.$refs.loading.hide();
			this.$emit('close');
		}
	}
};
</script>

<style lang="less" scoped>
/* 按钮去掉边框 */
button::after {
	border: none;
}
button {
	color: #66645d;
}

.canvas-content {
	.canvas-mask {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 100;
	}
	.canvas {
		position: fixed;
		top: 300%;
		// z-index: 1000;
		// transform: scale(0.3);
		// transform-origin: 0 0;
	}

	.preview-panel {
		position: fixed;
		left: 40rpx;
		right: 40rpx;
		transform: translateY(-50%);
		top: 50%;
		max-height: calc(100% - 80rpx);
		z-index: 101;
		border-radius: 20rpx;
		overflow: hidden;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		padding: 36rpx 0 0 0;
		.preview-panel-header {
			font-size: 36rpx;
			font-weight: 400;
			color: #66645d;
			text-align: center;
			line-height: 50rpx;
			padding: 0 40rpx;
		}
		.preview-panel-body {
			max-width: 590rpx;
			min-height: 591rpx;
			box-shadow: 0 4rpx 20rpx 0 rgba(102, 100, 93, 0.1);
			border-radius: 20rpx;
			margin: 20rpx 40rpx 0 40rpx;
			overflow-y: auto;
			.panel-image {
				width: 100%;
				min-height: 100%;
				vertical-align: middle;
			}
		}
		.preview-panel-footer {
			display: flex;
			margin-top: 40rpx;
			flex-shrink: 0;
			background-color: #f7f7f7;
			button {
				width: 50%;
				border-radius: 0;
				font-size: 30rpx;
				line-height: 90rpx;
				&::after {
					border-radius: 0;
					border: none;
				}
			}
		}
	}
}
</style>
